/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.ruralLibrary.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.model.S3Object;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.admin.api.dto.UserDTO;
import com.pig4cloud.pigx.admin.api.entity.SysRole;
import com.pig4cloud.pigx.admin.api.entity.SysUser;
import com.pig4cloud.pigx.admin.api.feign.RemoteDataScopeService;
import com.pig4cloud.pigx.admin.api.feign.RemoteUserService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.exception.ErrorCodes;
import com.pig4cloud.pigx.common.core.util.MsgUtils;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.excel.vo.ErrorMessage;
import com.pig4cloud.pigx.common.file.core.FileTemplate;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.ruralLibrary.api.entity.*;
import com.pig4cloud.pigx.ruralLibrary.api.dto.BookUserVo;
import com.pig4cloud.pigx.ruralLibrary.api.dto.userVo;
import com.pig4cloud.pigx.ruralLibrary.api.vo.BookUserVO;
import com.pig4cloud.pigx.ruralLibrary.mapper.BookUserMapper;
import com.pig4cloud.pigx.ruralLibrary.mapper.ObpCityMapper;
import com.pig4cloud.pigx.ruralLibrary.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pig
 * @date 2023-06-29 09:59:08
 */
@Slf4j
@Service
public class BookUserServiceImpl extends ServiceImpl<BookUserMapper, BookUserEntity> implements BookUserService {
	@Autowired(required = false)
	private BookUserMapper mapper;
	@Autowired(required = false)
	private ObpCityMapper cityMapper;
	@Autowired(required = false)
	private RemoteUserService sysUserService;
	@Autowired
	private FileTemplate fileTemplate;
	@Autowired
	private ObpCityService obpCityService;
	@Autowired
	private ObpAreaService obpAreaService;
	@Autowired
	private ObjStreetService objStreetService;
	@Autowired
	private ObpCommitteeService obpCommitteeService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private SysUserService sysUserService1;
	@Autowired(required = false)
	private RemoteDataScopeService remoteDataScopeService;
	private final Logger logger = LoggerFactory.getLogger(BookUserServiceImpl.class);

	/**
	 * 导入
	 *
	 * @param excelVOList
	 * @param bindingResult
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public R importUser(List<BookUserVo> excelVOList, BindingResult bindingResult) {

		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

		for (BookUserVo bookUserVo : excelVOList) {
			List<BookUserEntity> userList = this.list();
			Set<String> errorMsg = new HashSet<>();
			// 校验用户名是否存在
			boolean exsitUserName = userList.stream()
					.anyMatch(bookUser -> bookUserVo.getUserName().equals(bookUser.getUserName()));
			if (exsitUserName) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, bookUserVo.getUserName()));
			}

			LambdaQueryWrapper<ObpCityEntity> wrapperCity = Wrappers.lambdaQuery();
			wrapperCity.eq(ObpCityEntity::getCityName, bookUserVo.getCity());
			ObpCityEntity obpCityEntity = obpCityService.getOne(wrapperCity);
			if (obpCityEntity == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.MUNICIPAL, bookUserVo.getCity()));
			} else if (obpCityEntity.getCityCode() == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.MUNICIPAL, bookUserVo.getCity()));
			} else if (StrUtil.isNotBlank(obpCityEntity.getCityCode())) {
				bookUserVo.setCity(obpCityEntity.getCityCode());
			}
			LambdaQueryWrapper<ObpAreaEntity> wrapperArea = Wrappers.lambdaQuery();
			wrapperArea.eq(ObpAreaEntity::getAreaName, bookUserVo.getDistrict());
			ObpAreaEntity obpAreaEntity = obpAreaService.getOne(wrapperArea);
			if (obpAreaEntity == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.DISTRICT, bookUserVo.getDistrict()));
			} else if (obpAreaEntity.getAreaCode() == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.DISTRICT, bookUserVo.getDistrict()));
			} else if (StrUtil.isNotBlank(obpAreaEntity.getAreaCode())) {
				if (!obpCityEntity.getCityCode().equals(obpAreaEntity.getCityCode())) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.AREA, bookUserVo.getDistrict()));
				} else {
					bookUserVo.setDistrict(obpAreaEntity.getAreaCode());
				}
			}
			LambdaQueryWrapper<ObjStreetEntity> wrapperStreet = Wrappers.lambdaQuery();
			wrapperStreet.eq(ObjStreetEntity::getStreetName, bookUserVo.getVillage());
			ObjStreetEntity getVillage = objStreetService.getOne(wrapperStreet);
			if (getVillage == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.VILLAGE, bookUserVo.getVillage()));
			} else if (getVillage.getStreetCode() == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.VILLAGE, bookUserVo.getVillage()));
			} else if (StrUtil.isNotBlank(getVillage.getStreetCode())) {
				if (!obpAreaEntity.getAreaCode().equals(getVillage.getAreaCode())) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.AREA, bookUserVo.getVillage()));
				} else {
					bookUserVo.setVillage(getVillage.getStreetCode());
				}

			}

			LambdaQueryWrapper<ObpCommitteeEntity> wrapperCommittee = Wrappers.lambdaQuery();
			wrapperCommittee.eq(ObpCommitteeEntity::getCommitteeName, bookUserVo.getCommittee());
			ObpCommitteeEntity obpCommitteeEntity = obpCommitteeService.getOne(wrapperCommittee);
			if (obpCommitteeEntity == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.COMMITTEE, bookUserVo.getCommittee()));
			} else if (obpCommitteeEntity.getCommitteeCode() == null) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.COMMITTEE, bookUserVo.getCommittee()));
			} else if (StrUtil.isNotBlank(obpCommitteeEntity.getCommitteeCode())) {
				if (!getVillage.getStreetCode().equals(obpCommitteeEntity.getStreetCode())) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.AREA, bookUserVo.getCommittee()));
				} else {
					bookUserVo.setCommittee(obpCommitteeEntity.getCommitteeCode());
				}

			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				UserDTO userDTO = new UserDTO();
				BookUserEntity bookUserEntity = new BookUserEntity();
				BeanUtil.copyProperties(bookUserVo, bookUserEntity);
				String name = SecurityUtils.getUser().getName();
				bookUserEntity.setCreateName(name);
				bookUserEntity.setStatus("1");
				bookUserEntity.setUseStatus("1");
				SecurityUtils.getUser();
				LocalDateTime date = LocalDateTime.now();
				bookUserEntity.setCreateTime(date);
				List<Long> roles = new ArrayList<>();
				if (bookUserVo.getJurisdiction() == null || bookUserVo.getJurisdiction().equals("") || bookUserVo.getJurisdiction().equals("6")) {
					bookUserEntity.setJurisdiction("6");
				} else {
					if (bookUserVo.getJurisdiction().equals("1")) {
						roles.add(Long.valueOf("1675757770717044737"));
						userDTO.setRole(roles);
					} else if (bookUserVo.getJurisdiction().equals("2")) {
						roles.add(Long.valueOf("1675758246296592386"));
						userDTO.setRole(roles);
					} else if (bookUserVo.getJurisdiction().equals("3")) {
						roles.add(Long.valueOf("1675761537092984834"));
						userDTO.setRole(roles);
					} else if (bookUserVo.getJurisdiction().equals("4")) {
						roles.add(Long.valueOf("1675761877053906945"));
						userDTO.setRole(roles);
					} else if (bookUserVo.getJurisdiction().equals("5")) {
						roles.add(Long.valueOf("1682299000997376001"));
						userDTO.setRole(roles);
					}

					userDTO.setUserId(bookUserEntity.getId());
					userDTO.setPassword(bookUserEntity.getUserCode());
					userDTO.setUsername(bookUserEntity.getUserName());
					userDTO.setPhone(bookUserEntity.getUserName());
					userDTO.setLockFlag("0");
					userDTO.setDeptId(Long.valueOf("1675767701453176833"));
					List<Long> post = new ArrayList<>();
					post.add(Long.valueOf("1675767581236035586"));
					userDTO.setPost(post);
					sysUserService.user(userDTO, SecurityConstants.FROM_IN);
				}

				this.save(bookUserEntity);
			} else {
				// 数据不合法情况
				errorMessageList.add(new ErrorMessage(bookUserVo.getLineNum(), errorMsg));
			}

		}

		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}

		return R.ok(null, MsgUtils.getMessage(ErrorCodes.SYS_USER_IMPORT_SUCCEED));
	}

	/**
	 * 导出
	 */
	public List<BookUserVo> export(userVo userVo) {
		List<BookUserVo> bookUserVos = new ArrayList<>();
		String location = null;
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUserEntity = this.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (!bookUserEntity.getJurisdiction().equals("0")) {
				if (bookUserEntity.getJurisdiction().equals("1")) {
					location = bookUserEntity.getProvince();
				} else if (bookUserEntity.getJurisdiction().equals("2")) {
					location = bookUserEntity.getCity();
				} else if (bookUserEntity.getJurisdiction().equals("3")) {
					location = bookUserEntity.getDistrict();
				} else if (bookUserEntity.getJurisdiction().equals("4")) {
					location = bookUserEntity.getVillage();
				} else if (bookUserEntity.getJurisdiction().equals("5")) {
					location = bookUserEntity.getCommittee();
				}
			}
		}
		List<userVo> user = mapper.getUser(null, userVo, Integer.parseInt(bookUserEntity.getJurisdiction()), location);
		for (userVo entity : user) {
			BookUserVo bookUserVo = new BookUserVo();
			BeanUtil.copyProperties(entity, bookUserVo);
			bookUserVo.setCity(entity.getCityName());
			bookUserVo.setDistrict(entity.getAreaName());
			bookUserVo.setVillage(entity.getStreetName());
			bookUserVo.setCommittee(entity.getCommitteeName());
			bookUserVos.add(bookUserVo);
		}
		return bookUserVos;
	}

	/**
	 * 删除
	 *
	 * @param ids
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R remove(Long[] ids) {
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUser = this.getOne(userwrapper);

		List<Long> list = new ArrayList<Long>();
		List<String> userNames = new ArrayList<>();
		List<BookUserEntity> entities = new ArrayList<>();
		for (Long i : ids) {
			if (!list.contains(i)) {
				list.add(i);
			}
		}
		for (Long id : list) {
			BookUserEntity bookUserEntity = this.getById(id);
			if (bookUserEntity.getJurisdiction().equals("0")) {
				return R.failed("管理员无法删除");
			}
			if (bookUserEntity.getJurisdiction().equals(bookUser.getJurisdiction())) {
				return R.failed("同等级无权限修改");
			}
			userNames.add(bookUserEntity.getUserName());
			bookUserEntity.setStatus("0");
			entities.add(bookUserEntity);
		}

		this.updateBatchById(entities);
		List<SysUser> sysUsers = sysUserService.selectByUser(userNames, SecurityConstants.FROM_IN);
		Long[] userIdArray = sysUsers.stream().map(SysUser::getUserId).toArray(Long[]::new);
		if (userIdArray.length != 0) {
			R r = sysUserService.delUser(userIdArray, SecurityConstants.FROM_IN);
			return r;
		}
		return R.ok("删除成功");
	}

	/**
	 * 新增用户
	 *
	 * @param bookUser
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveUserR(BookUserVO bookUser) {
		List<BookUserEntity> userList = this.list();
		boolean exsitUserName = userList.stream()
				.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
		if (exsitUserName) {
			return R.failed("重复用户名");
		}
		String smsCode = (String) redisTemplate.opsForValue().get("sms-code-".concat(bookUser.getPhoneNumber()));
		if (Objects.nonNull(smsCode)) {
			if (!Objects.equals(bookUser.getVerifyCode(), smsCode.toString())) {
				return R.failed("验证码错误");
			}
		} else {
			return R.failed("验证码错误");
		}
		BookUserEntity bookUserEntity = new BookUserEntity();
		BeanUtils.copyProperties(bookUser, bookUserEntity);
		bookUserEntity.setUserCode(convertMD5(bookUser.getUserCode()));
		bookUserEntity.setProvince("河南省");
		bookUserEntity.setStatus("1");
		bookUserEntity.setUseStatus("1");
		LocalDateTime date = LocalDateTime.now();
		bookUserEntity.setCreateTime(date);
		bookUserEntity.setJurisdiction("6");

		if (StringUtils.isNotBlank(bookUser.getCreateName())) {
			bookUser.setCreateName("小程序");
			String md5 = convertMD5(bookUser.getUserCode());
			bookUser.setUserCode(md5);
		}

		return R.ok(this.save(bookUserEntity));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveUser(BookUserEntity bookUser) {
		//只能增加同级和他以下级别的管理员   不能增加用户
		//将手机号作为用户名登录，只能增加本区的
		//首先先判断是否注册的是管理员
		if (bookUser.getJurisdiction().equals("6")) {
			return R.failed("暂无法注册普通用户");
		} else {
			List<String> userNames = new ArrayList<>();
			userNames.add(bookUser.getPhoneNumber());
			List<SysUser> sysUsers = sysUserService.selectByUser(userNames, SecurityConstants.FROM_IN);
			if (sysUsers.size() != 0) {
				return R.failed("用户已存在");
			} else {
				R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
						.map(String::valueOf)
						.collect(Collectors.toList()));
				logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
				if (listR != null) {
					if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
							|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
						//随便增加各级管理员
						//向用户表插入数据
						List<BookUserEntity> userList = this.list();
						boolean exsitUserName = userList.stream()
								.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
						if (exsitUserName) {
							return R.failed("重复用户名");
						}
						bookUser.setProvince("河南省");
						bookUser.setStatus("1");
						bookUser.setUseStatus("1");
						LocalDateTime date = LocalDateTime.now();
						bookUser.setCreateTime(date);
						bookUser.setCity(bookUser.getCityName());
						bookUser.setVillage(bookUser.getStreetName());
						bookUser.setDistrict(bookUser.getAreaName());
						bookUser.setCommittee(bookUser.getCommitteeName());
						if (StringUtils.isNotBlank(bookUser.getCreateName())) {
							bookUser.setCreateName("网站");
							String md5 = convertMD5(bookUser.getUserCode());
							bookUser.setUserCode(md5);
						}
						this.save(bookUser);
						//向系统管理表插入数据
						LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
						bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserName, bookUser.getUserName());
						BookUserEntity one = this.getOne(bookUserEntityLambdaQueryWrapper);
						UserDTO userDTO = new UserDTO();
						List<Long> roles = new ArrayList<>();
						if (bookUser.getJurisdiction().equals("1")) {
							roles.add(Long.valueOf("1675757770717044737"));
							userDTO.setRole(roles);
						} else if (bookUser.getJurisdiction().equals("2")) {
							roles.add(Long.valueOf("1675758246296592386"));
							userDTO.setRole(roles);
						} else if (bookUser.getJurisdiction().equals("3")) {
							roles.add(Long.valueOf("1675761537092984834"));
							userDTO.setRole(roles);
						} else if (bookUser.getJurisdiction().equals("4")) {
							roles.add(Long.valueOf("1675761877053906945"));
							userDTO.setRole(roles);
						} else if (bookUser.getJurisdiction().equals("5")) {
							roles.add(Long.valueOf("1682299000997376001"));
							userDTO.setRole(roles);
						}
						userDTO.setPassword(bookUser.getUserCode());
						userDTO.setUsername(bookUser.getUserName());
						userDTO.setPhone(bookUser.getPhoneNumber());
						userDTO.setLockFlag("0");
						userDTO.setDeptId(Long.valueOf("1675767701453176833"));
						List<Long> post = new ArrayList<>();
						post.add(Long.valueOf("1675767581236035586"));
						userDTO.setPost(post);
						userDTO.setUserId(one.getId());
						sysUserService.user(userDTO, SecurityConstants.FROM_IN);
					}
					if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
						//只能增加市级管理员
						if (Integer.parseInt(bookUser.getJurisdiction()) < 2) {
							return R.failed("该用户无权限");
						} else {
							//只能增加本市的
							BookUserEntity bookUser1 = this.getById(SecurityUtils.getUser().getId());
							if (bookUser1 != null) {
								if (!bookUser1.getCity().equals( bookUser.getCityName())) {
									return R.failed("该用户暂无此权限");
								} else {
									//向用户表插入数据
									List<BookUserEntity> userList = this.list();
									boolean exsitUserName = userList.stream()
											.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
									if (exsitUserName) {
										return R.failed("重复用户名");
									}
									bookUser.setProvince("河南省");
									bookUser.setStatus("1");
									bookUser.setUseStatus("1");
									LocalDateTime date = LocalDateTime.now();
									bookUser.setCreateTime(date);
									bookUser.setCity(bookUser.getCityName());
									bookUser.setVillage(bookUser.getStreetName());
									bookUser.setDistrict(bookUser.getAreaName());
									bookUser.setCommittee(bookUser.getCommitteeName());
									if (StringUtils.isNotBlank(bookUser.getCreateName())) {
										bookUser.setCreateName("网站");
										String md5 = convertMD5(bookUser.getUserCode());
										bookUser.setUserCode(md5);
									}
									this.save(bookUser);
									//向系统管理表插入数据
									LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
									bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserName, bookUser.getUserName());
									BookUserEntity one = this.getOne(bookUserEntityLambdaQueryWrapper);
									UserDTO userDTO = new UserDTO();
									List<Long> roles = new ArrayList<>();
									if (bookUser.getJurisdiction().equals("1")) {
										roles.add(Long.valueOf("1675757770717044737"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("2")) {
										roles.add(Long.valueOf("1675758246296592386"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("3")) {
										roles.add(Long.valueOf("1675761537092984834"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("4")) {
										roles.add(Long.valueOf("1675761877053906945"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("5")) {
										roles.add(Long.valueOf("1682299000997376001"));
										userDTO.setRole(roles);
									}
									userDTO.setPassword(bookUser.getUserCode());
									userDTO.setUsername(bookUser.getUserName());
									userDTO.setPhone(bookUser.getPhoneNumber());
									userDTO.setLockFlag("0");
									userDTO.setDeptId(Long.valueOf("1675767701453176833"));
									List<Long> post = new ArrayList<>();
									post.add(Long.valueOf("1675767581236035586"));
									userDTO.setPost(post);
									userDTO.setUserId(one.getId());
									sysUserService.user(userDTO, SecurityConstants.FROM_IN);
								}
							}
						}
					}
					if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
						//只能增加区县级管理员和以下
						if (Integer.parseInt(bookUser.getJurisdiction()) < 3) {
							return R.failed("该用户无权限");
						} else {
							//只能增加本区的
							BookUserEntity bookUser1 = this.getById(SecurityUtils.getUser().getId());
							if (bookUser1 != null) {
								if (!bookUser1.getDistrict() .equals(bookUser.getAreaName()) ) {
									return R.failed("该用户暂无此权限");
								} else {
									//向用户表插入数据
									List<BookUserEntity> userList = this.list();
									boolean exsitUserName = userList.stream()
											.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
									if (exsitUserName) {
										return R.failed("重复用户名");
									}
									bookUser.setProvince("河南省");
									bookUser.setStatus("1");
									bookUser.setUseStatus("1");
									LocalDateTime date = LocalDateTime.now();
									bookUser.setCreateTime(date);
									bookUser.setCity(bookUser.getCityName());
									bookUser.setVillage(bookUser.getStreetName());
									bookUser.setDistrict(bookUser.getAreaName());
									bookUser.setCommittee(bookUser.getCommitteeName());
									if (StringUtils.isNotBlank(bookUser.getCreateName())) {
										bookUser.setCreateName("网站");
										String md5 = convertMD5(bookUser.getUserCode());
										bookUser.setUserCode(md5);
									}
									this.save(bookUser);
									//向系统管理表插入数据
									LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
									bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserName, bookUser.getUserName());
									BookUserEntity one = this.getOne(bookUserEntityLambdaQueryWrapper);
									UserDTO userDTO = new UserDTO();
									List<Long> roles = new ArrayList<>();
									if (bookUser.getJurisdiction().equals("1")) {
										roles.add(Long.valueOf("1675757770717044737"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("2")) {
										roles.add(Long.valueOf("1675758246296592386"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("3")) {
										roles.add(Long.valueOf("1675761537092984834"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("4")) {
										roles.add(Long.valueOf("1675761877053906945"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("5")) {
										roles.add(Long.valueOf("1682299000997376001"));
										userDTO.setRole(roles);
									}
									userDTO.setPassword(bookUser.getUserCode());
									userDTO.setUsername(bookUser.getUserName());
									userDTO.setPhone(bookUser.getPhoneNumber());
									userDTO.setLockFlag("0");
									userDTO.setDeptId(Long.valueOf("1675767701453176833"));
									List<Long> post = new ArrayList<>();
									post.add(Long.valueOf("1675767581236035586"));
									userDTO.setPost(post);
									userDTO.setUserId(one.getId());
									sysUserService.user(userDTO, SecurityConstants.FROM_IN);
								}
							}
						}
					}
					if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
						//只能增加乡级管理员和以下
						if (Integer.parseInt(bookUser.getJurisdiction()) < 4) {
							return R.failed("该用户无权限");
						} else {
							//只能增加本市的
							BookUserEntity bookUser1 = this.getById(SecurityUtils.getUser().getId());
							if (bookUser1 != null) {
								if (!bookUser1.getVillage() .equals(bookUser.getStreetName())) {
									return R.failed("该用户暂无此权限");
								} else {
									//向用户表插入数据
									List<BookUserEntity> userList = this.list();
									boolean exsitUserName = userList.stream()
											.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
									if (exsitUserName) {
										return R.failed("重复用户名");
									}
									bookUser.setProvince("河南省");
									bookUser.setStatus("1");
									bookUser.setUseStatus("1");
									LocalDateTime date = LocalDateTime.now();
									bookUser.setCreateTime(date);
									bookUser.setCity(bookUser.getCityName());
									bookUser.setVillage(bookUser.getStreetName());
									bookUser.setDistrict(bookUser.getAreaName());
									bookUser.setCommittee(bookUser.getCommitteeName());
									if (StringUtils.isNotBlank(bookUser.getCreateName())) {
										bookUser.setCreateName("网站");
										String md5 = convertMD5(bookUser.getUserCode());
										bookUser.setUserCode(md5);
									}
									this.save(bookUser);
									//向系统管理表插入数据
									LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
									bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserName, bookUser.getUserName());
									BookUserEntity one = this.getOne(bookUserEntityLambdaQueryWrapper);
									UserDTO userDTO = new UserDTO();
									List<Long> roles = new ArrayList<>();
									if (bookUser.getJurisdiction().equals("1")) {
										roles.add(Long.valueOf("1675757770717044737"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("2")) {
										roles.add(Long.valueOf("1675758246296592386"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("3")) {
										roles.add(Long.valueOf("1675761537092984834"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("4")) {
										roles.add(Long.valueOf("1675761877053906945"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("5")) {
										roles.add(Long.valueOf("1682299000997376001"));
										userDTO.setRole(roles);
									}
									userDTO.setPassword(bookUser.getUserCode());
									userDTO.setUsername(bookUser.getUserName());
									userDTO.setPhone(bookUser.getPhoneNumber());
									userDTO.setLockFlag("0");
									userDTO.setDeptId(Long.valueOf("1675767701453176833"));
									List<Long> post = new ArrayList<>();
									post.add(Long.valueOf("1675767581236035586"));
									userDTO.setPost(post);
									userDTO.setUserId(one.getId());
									sysUserService.user(userDTO, SecurityConstants.FROM_IN);
								}
							}
						}
					}
					if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
						//只能增加村级管理员
						if (Integer.parseInt(bookUser.getJurisdiction()) < 5) {
							return R.failed("该用户无权限");
						} else {
							//只能增加本市的
							BookUserEntity bookUser1 = this.getById(SecurityUtils.getUser().getId());
							if (bookUser1 != null) {
								if (!bookUser1.getCommittee().equals(bookUser.getCommitteeName())) {
									return R.failed("该用户暂无此权限");
								} else {
									//向用户表插入数据
									List<BookUserEntity> userList = this.list();
									boolean exsitUserName = userList.stream()
											.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
									if (exsitUserName) {
										return R.failed("重复用户名");
									}
									bookUser.setProvince("河南省");
									bookUser.setStatus("1");
									bookUser.setUseStatus("1");
									LocalDateTime date = LocalDateTime.now();
									bookUser.setCreateTime(date);
									bookUser.setCity(bookUser.getCityName());
									bookUser.setVillage(bookUser.getStreetName());
									bookUser.setDistrict(bookUser.getAreaName());
									bookUser.setCommittee(bookUser.getCommitteeName());
									if (StringUtils.isNotBlank(bookUser.getCreateName())) {
										bookUser.setCreateName("网站");
										String md5 = convertMD5(bookUser.getUserCode());
										bookUser.setUserCode(md5);
									}
									this.save(bookUser);
									//向系统管理表插入数据
									LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
									bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserName, bookUser.getUserName());
									BookUserEntity one = this.getOne(bookUserEntityLambdaQueryWrapper);
									UserDTO userDTO = new UserDTO();
									List<Long> roles = new ArrayList<>();
									if (bookUser.getJurisdiction().equals("1")) {
										roles.add(Long.valueOf("1675757770717044737"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("2")) {
										roles.add(Long.valueOf("1675758246296592386"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("3")) {
										roles.add(Long.valueOf("1675761537092984834"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("4")) {
										roles.add(Long.valueOf("1675761877053906945"));
										userDTO.setRole(roles);
									} else if (bookUser.getJurisdiction().equals("5")) {
										roles.add(Long.valueOf("1682299000997376001"));
										userDTO.setRole(roles);
									}
									userDTO.setPassword(bookUser.getUserCode());
									userDTO.setUsername(bookUser.getUserName());
									userDTO.setPhone(bookUser.getPhoneNumber());
									userDTO.setLockFlag("0");
									userDTO.setDeptId(Long.valueOf("1675767701453176833"));
									List<Long> post = new ArrayList<>();
									post.add(Long.valueOf("1675767581236035586"));
									userDTO.setPost(post);
									userDTO.setUserId(one.getId());
									sysUserService.user(userDTO, SecurityConstants.FROM_IN);
								}
							}
						}
					}
				}
			}
		}
		return R.ok(Boolean.TRUE);

//
//    if(!bookUser.getJurisdiction().equals("6"))
//	{
//		List<String> userNames = new ArrayList<>();
//		userNames.add(bookUser.getUserName());
//		List<SysUser> sysUsers = sysUserService.selectByUser(userNames, SecurityConstants.FROM_IN);
//
////		LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
////		sysUserLambdaQueryWrapper.eq(SysUser::getUsername,bookUser.getUserName());
//	      if(sysUsers.size()==0)
//		  {
//			  return R.failed("无效数据");
//		  }else{
//			  SysUser one = sysUsers.get(0);
////			  SysUser one = sysUserService1.getOne(sysUserLambdaQueryWrapper);
//			  bookUser.setId(one.getUserId());
//			  List<BookUserEntity> userList = this.list();
//			  boolean exsitUserName = userList.stream()
//					  .anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
//			  if (exsitUserName) {
//				  return R.failed("重复用户名");
//			  }
//			  bookUser.setProvince("河南省");
//			  bookUser.setStatus("1");
//			  bookUser.setUseStatus("1");
//			  LocalDateTime date = LocalDateTime.now();
//			  bookUser.setCreateTime(date);
//			  bookUser.setJurisdiction(bookUser.getJurisdiction());
//			  bookUser.setCity(bookUser.getCityName());
//              bookUser.setVillage(bookUser.getStreetName());
//              bookUser.setDistrict(bookUser.getAreaName());
//              bookUser.setCommittee(bookUser.getCommitteeName());
// 			  if (StringUtils.isNotBlank(bookUser.getCreateName())){
//				  bookUser.setCreateName("小程序");
//				  String md5 = convertMD5(bookUser.getUserCode());
//				  bookUser.setUserCode(md5);
//			  }
//		  }
//
//	}else{
//    	//普通用户
//		List<BookUserEntity> userList = this.list();
//		boolean exsitUserName = userList.stream()
//				.anyMatch(User -> bookUser.getUserName().equals(User.getUserName()));
//		if (exsitUserName) {
//			return R.failed("重复用户名");
//		}
//		bookUser.setProvince("河南省");
//		bookUser.setStatus("1");
//		bookUser.setUseStatus("1");
//		LocalDateTime date = LocalDateTime.now();
//		bookUser.setCreateTime(date);
//		bookUser.setJurisdiction("6");
//		bookUser.setCity(bookUser.getCityName());
//		bookUser.setVillage(bookUser.getStreetName());
//		bookUser.setDistrict(bookUser.getAreaName());
//		bookUser.setCommittee(bookUser.getCommitteeName());
//		if (StringUtils.isNotBlank(bookUser.getCreateName())){
//			bookUser.setCreateName("小程序");
//			String md5 = convertMD5(bookUser.getUserCode());
//			bookUser.setUserCode(md5);
//		}
//	}
//		return R.ok(this.save(bookUser));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R update(userVo userVo) {
		String password = convertMD5(convertMD5(userVo.getUserCode()));
		BookUserEntity byId = this.getById(userVo.getId());
		BookUserEntity bookUser = new BookUserEntity();
		BeanUtils.copyProperties(userVo, bookUser);
		if (!byId.getUserCode().equals(bookUser.getUserCode())) {
			password = bookUser.getUserCode();
			String md5 = convertMD5(bookUser.getUserCode());
			bookUser.setUserCode(md5);
		}
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUserEntity = this.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction()) && StrUtil.isNotBlank(bookUser.getJurisdiction())) {
			if (Integer.parseInt(bookUserEntity.getJurisdiction()) >= Integer.parseInt(bookUser.getJurisdiction())) {
				return R.failed("该用户无权限");
			}
			if (bookUserEntity.getJurisdiction().equals(byId.getJurisdiction())) {
				return R.failed("同等级无权限修改");
			}
		} else {
			return R.failed("该用户角色异常");
		}
		if (userVo.getCityName().startsWith("41")) {
			bookUser.setCity(userVo.getCityName());
			bookUser.setDistrict(userVo.getAreaName());
			bookUser.setVillage(userVo.getStreetName());
			bookUser.setCommittee(userVo.getCommitteeName());
		} else {
			bookUser.setCity(userVo.getCity());
			bookUser.setDistrict(userVo.getDistrict());
			bookUser.setVillage(userVo.getVillage());
			bookUser.setCommittee(userVo.getCommittee());
		}

		R user = new R();
		this.updateById(bookUser);
		UserDTO userDTO = new UserDTO();
		List<Long> roles = new ArrayList<>();
		List<String> userNames = new ArrayList<>();
		userNames.add(bookUser.getUserName());
		List<SysUser> sysUsers = sysUserService.selectByUser(userNames, SecurityConstants.FROM_IN);
		if (!bookUser.getJurisdiction().equals(byId.getJurisdiction())) {
			if (StrUtil.isNotBlank(bookUser.getJurisdiction())) {
				if (bookUser.getJurisdiction().equals("1")) {
					roles.add(Long.valueOf("1675757770717044737"));
					userDTO.setRole(roles);
				} else if (bookUser.getJurisdiction().equals("2")) {
					roles.add(Long.valueOf("1675758246296592386"));
					userDTO.setRole(roles);
				} else if (bookUser.getJurisdiction().equals("3")) {
					roles.add(Long.valueOf("1675761537092984834"));
					userDTO.setRole(roles);
				} else if (bookUser.getJurisdiction().equals("4")) {
					roles.add(Long.valueOf("1675761877053906945"));
					userDTO.setRole(roles);
				} else if (bookUser.getJurisdiction().equals("5")) {
					roles.add(Long.valueOf("1682299000997376001"));
					userDTO.setRole(roles);
				} else if (bookUser.getJurisdiction().equals("6")) {
					Long[] userIdArray = sysUsers.stream().map(SysUser::getUserId).toArray(Long[]::new);
					return sysUserService.delUser(userIdArray, SecurityConstants.FROM_IN);
				}
				if (byId.getJurisdiction().equals("6")) {
					userDTO.setUserId(bookUser.getId());
					userDTO.setPassword(password);
					userDTO.setUsername(bookUser.getUserName());
					userDTO.setPhone(bookUser.getUserName());
					userDTO.setLockFlag("0");
					userDTO.setDeptId(Long.valueOf("1675767701453176833"));
					user = sysUserService.user(userDTO, SecurityConstants.FROM_IN);
				} else {
					Long id = bookUser.getId();
					userDTO.setUserId(id);
					userDTO.setUsername(bookUser.getUserName());
					userDTO.setPassword(password);
					user = sysUserService.update(userDTO, SecurityConstants.FROM_IN);
				}

			}

		}

		return user;
	}

	@Override
	public void getFile(String bucket, String fileName, HttpServletResponse response) {
		try (S3Object s3Object = fileTemplate.getObject(bucket, fileName)) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.copy(s3Object.getObjectContent(), response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常: {}", e.getLocalizedMessage());
		}
	}

	@Override
	public R getUser(Page page, userVo userVo) {
		String location = null;
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUserEntity = this.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (!bookUserEntity.getJurisdiction().equals("0")) {
				if (bookUserEntity.getJurisdiction().equals("1")) {
					location = bookUserEntity.getProvince();
				} else if (bookUserEntity.getJurisdiction().equals("2")) {
					location = bookUserEntity.getCity();
				} else if (bookUserEntity.getJurisdiction().equals("3")) {
					location = bookUserEntity.getDistrict();
				} else if (bookUserEntity.getJurisdiction().equals("4")) {
					location = bookUserEntity.getVillage();
				} else if (bookUserEntity.getJurisdiction().equals("5")) {
					location = bookUserEntity.getCommittee();
				} else {
					return R.failed("没有权限");
				}
			}
		} else {
			return R.failed("没有权限");
		}
		if (StrUtil.isNotBlank(userVo.getJurisdiction())) {
			if (Integer.parseInt(bookUserEntity.getJurisdiction()) > Integer.parseInt(userVo.getJurisdiction())) {
				return R.failed("没有权限");
			}
		}
		return R.ok(page.setRecords(mapper.getUser(page, userVo, Integer.parseInt(bookUserEntity.getJurisdiction()), location)));
	}

	@Override
	public R getOne(Long id) {
		return R.ok(mapper.getOne(id));
	}

	@Override
	public R login(String userName, String userCode) {
		LambdaQueryWrapper<BookUserEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(BookUserEntity::getUserName, userName);
		BookUserEntity one = this.getOne(wrapper);
		if (one == null) {
			return R.failed("账号错误或该账号暂无注册");
		}
		String md5 = convertMD5(userCode);
		if (md5.equals(one.getUserCode())) {
			return R.ok("登录成功");
		} else {
			return R.failed("密码错误");
		}
	}


	/**
	 * 解密
	 *
	 * @param encryptedText
	 * @return
	 */
	public String decode(String encryptedText) {
		String password = "0123456789ABCDEF0123456789ABCDEF"; // 解密密码
		try {
			// Base64 解码密文
			Security.addProvider(new BouncyCastleProvider());

			// Base64 解码密文
			byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);

			// 创建 AES 密钥规范
			SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "AES");

			// 创建 AES 解密器，并设置 ECB 模式和 PKCS7 填充方式
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);

			// 解密
			byte[] decryptedBytes = cipher.doFinal(decodedBytes);
			String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);

			return decryptedText;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String convertMD5(String inStr) {

		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;

	}
}
